package com.mangguo.tingjian.user.controller;

import com.mangguo.tingjian.common.Result;
import com.mangguo.tingjian.user.controller.req.UserImageReq;
import com.mangguo.tingjian.user.dto.*;
import com.mangguo.tingjian.user.service.IUserImageService;
import com.mangguo.tingjian.util.CityUtils;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.atomic.AtomicLong;

@RestController
@RequestMapping("/user/user-image")
@AllArgsConstructor
public class UserImageController {

    private final IUserImageService userImageService;
    
    /**
     * 用户数按月份统计
     * @return
     */
        @PostMapping("/unique-imei/month")
    public Result<List<CountResult>> userCountByMonth(@RequestBody UserImageReq userImageReq){
        return Result.success(userImageService.countUniqueImeiByMonth(userImageReq));
    }
    
    /**
     * 渠道数前五
     * @return
     */
    @PostMapping("/channel")
    public Result<List<ChannelResultDto>> userImageCountByChannelBetweenDate(@RequestBody UserImageReq userImageReq){
        List<ChannelResultDto> channelResultDtos = new LinkedList<>();
        List<ChannelResult> channelResults = userImageService.countUniqueImeiByChannelIdBetweenDate(userImageReq);
        channelResults.stream()
                .filter(e -> e.getChannelId() != null)
                .forEach(e -> channelResultDtos.add(new ChannelResultDto(e.getCount(), e.getChannelId())));
        channelResults.stream()
                .filter(e -> e.getSubchannelId() != null)
                .forEach(e -> channelResultDtos.add(new ChannelResultDto(e.getCount(), e.getSubchannelId())));
        channelResultDtos.sort((o1, o2) -> Math.toIntExact(o2.getCount() - o1.getCount()));
        return Result.success(channelResultDtos);
    }

    /**
     * 筛选城市前五
     * @return
     */
    @PostMapping("/city")
    public Result<List<CityResult>> userImageCountByCityBetweenDate(@RequestBody UserImageReq userImageReq){
        List<CityResult> cityResults = userImageService.countUniqueImeiByCityBetweenDate(userImageReq);
        cityResults.forEach(cityResult -> cityResult.setName(CityUtils.getCityName(cityResult.getCity())));
        return Result.success(cityResults);
    }

    /**
     * 全部城市
     * @return
     */
    @PostMapping("/city/all")
    public Result<List<CityResult>> userImageCountForAllCityBetweenDate(@RequestBody UserImageReq userImageReq){
        List<CityResult> cityResults = userImageService.countUniqueImeiForAllCityBetweenDate(userImageReq);
        cityResults.forEach(cityResult -> cityResult.setName(CityUtils.getCityName(cityResult.getCity())));
        return Result.success(cityResults);
    }

    /**
     * 筛选省份前五
     * @return
     */
    @PostMapping("/province")
    public Result<List<ProvinceResult>> userImageCountByProvinceBetweenDate(@RequestBody UserImageReq userImageReq){
        List<ProvinceResult> provinceResults = userImageService.countUniqueImeiByProvinceBetweenDate(userImageReq);
        provinceResults.forEach(provinceResult -> provinceResult.setName(CityUtils.getProvinceName(provinceResult.getProvince())));
        return Result.success(provinceResults);
    }

    /**
     * 全部省份数据
     * @return
     */
    @PostMapping("/province/all")
    public Result<List<ProvinceResult>> userImageCountForAllProvinceBetweenDate(@RequestBody UserImageReq userImageReq){
        List<ProvinceResult> provinceResults = userImageService.countUniqueImeiForAllProvinceBetweenDate(userImageReq);
        provinceResults.forEach(provinceResult -> provinceResult.setName(CityUtils.getProvinceName(provinceResult.getProvince())));
        return Result.success(provinceResults);
    }

    /**
     * 手机品牌前五百分比
     * @return
     */
    @PostMapping("/platform")
    public Result<List<PlatformResult>> userImageCountByPlatformBetweenDate(@RequestBody UserImageReq userImageReq){
        List<PlatformResult> list = userImageService.countUniqueImeiByPlatformBetweenDate(userImageReq);
        AtomicLong sum = new AtomicLong(0L);
        list.forEach(platformResult -> sum.addAndGet(platformResult.getCount()));
        list.forEach(platformResult -> platformResult.setRatio(platformResult.getCount().doubleValue() / sum.doubleValue()));
        if (list.size() > 5){
            PlatformResult other = PlatformResult.builder().platform("其他").count(0L).ratio(0d).build();
            for (int i = 5; i < list.size(); i++){
                other.setCount(other.getCount() + list.get(i).getCount());
                other.setRatio(other.getRatio() + list.get(i).getRatio());
            }
            list = list.subList(0 ,5);
            list.add(other);
        }
        return Result.success(list);
    }


    /**
     * 手机系统
     * @return
     */
    @PostMapping("/system")
    public Result<List<SystemResult>> userImageCountBySystemBetweenDate(@RequestBody UserImageReq userImageReq){
        List<SystemResult> list = userImageService.countUniqueImeiBySystemBetweenDate(userImageReq);
        AtomicLong sumAndroid = new AtomicLong(0L);
        AtomicLong sumIos = new AtomicLong(0L);
        list.forEach(e -> {
            if (e.getOsid().equalsIgnoreCase("ios")){
                sumIos.addAndGet(e.getCount());
            }else if(e.getOsid().equalsIgnoreCase("android")){
                sumAndroid.addAndGet(e.getCount());
            }
        });
        list.forEach(e -> {
            if (e.getOsid().equalsIgnoreCase("ios")){
                e.setRatio(e.getCount().doubleValue() / sumIos.doubleValue());
            }else if(e.getOsid().equalsIgnoreCase("android")){
                e.setRatio(e.getCount().doubleValue() / sumAndroid.doubleValue());
            }
        });
        return Result.success(list);
    }

    /**
     * 获取所有渠道号
     * @param tableName
     * @return
     */
    @GetMapping("/channel/{tableName}")
    public  Result<Set<String>> getAllChannel(@PathVariable("tableName") String tableName){
        return Result.success(userImageService.getAllChannel(tableName));
    }

}
